package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     *  分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());

        //执行查询
        List<SetmealVO> setmealList = setmealMapper.pageQuery(setmealPageQueryDTO);

        //封装结果并返回
        Page<SetmealVO> setmealPage = (Page<SetmealVO>) setmealList;
        return new PageResult(setmealPage.getTotal(), setmealPage.getResult());
    }

    /**
     *  新增套餐
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDTO setmealDTO) {
        //保存套餐基本信息
        Setmeal setmeal = Setmeal.builder()
                .status(StatusConstant.DISABLE)//默认为禁用
                .build();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.insert(setmeal);

        //保存套餐的菜品信息(在套餐菜品关系表中维护)
        saveSetmealDish(setmealDTO, setmeal.getId());
    }

    /**
     *  根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public SetmealVO getById(Long id) {
       // 根据id查询套餐基本信息
        SetmealVO setmealVO = setmealMapper.getById(id);

        // 根据id查询套餐菜品关系数据
        List<SetmealDish> setmealDishes = setmealDishMapper.getDishesBySetmealId(id);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    /**
     *  修改套餐
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        // 修改套餐基本信息
        Setmeal setmeal = Setmeal.builder().build();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.update(setmeal);

        // 先删除套餐的菜品关系数据
        setmealDishMapper.deleteBySetmealId(Collections.singletonList(setmealDTO.getId()));

        // 再插入套餐的菜品关系数据
        saveSetmealDish(setmealDTO, setmealDTO.getId());
    }

    /**
     *  起售停售套餐
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //如果是起售
        if (Objects.equals(status, StatusConstant.ENABLE)){
            //查询套餐中菜品的状态
            List<SetmealDish> dishesBySetmealId = setmealDishMapper.getDishesBySetmealId(id);
            if (dishesBySetmealId == null || dishesBySetmealId.size() == 0){
                //如果套餐中没有菜品，则不能起售
                throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
            }
            List<Long> dishIds = dishesBySetmealId.stream().map(SetmealDish::getDishId).toList();
            Long count = dishMapper.countStatusByIds(dishIds, StatusConstant.DISABLE);
            //如果套餐中有停售的菜品，则不能起售
            if (count > 0){
                throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
            }
        }

        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.update(setmeal);

    }

    /**
     *  批量删除套餐
     * @param ids
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        //起售的套餐不能删除
        Long count = setmealMapper.getStatusById(ids, StatusConstant.ENABLE);
        if (count > 0){
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }

        //删除套餐的基本信息
        setmealMapper.deleteByIds(ids);
        //删除套餐的菜品关系数据
        setmealDishMapper.deleteBySetmealId(ids);
    }


    /**
     *  添加套餐的菜品关系数据
     * @param setmealDTO
     * @param id
     */
    private void saveSetmealDish(SetmealDTO setmealDTO, Long id) {
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (setmealDishes == null || setmealDishes.size() == 0){
            return;
        }
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(id);
        });
        setmealDishMapper.insertBatch(setmealDishes);
    }

    /**
     * 根据分类id查询套餐信息
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Setmeal> getSetmealsByCategoryId(Long categoryId) {
        return setmealMapper.getByCategoryId(categoryId);
    }

    /**
     * 查询套餐中的菜品
     *
     * @param setmealId
     * @return
     */
    @Override
    public List<DishItemVO> getDishesBySetmealId(Long setmealId) {
        return dishMapper.getBysetmealId(setmealId);
    }
}
